package rs.mbs2.epics.server.servlet;

import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import rs.mbs2.epics.server.entity.Album;
import rs.mbs2.epics.server.entity.Comment;
import rs.mbs2.epics.server.entity.Photo;
import rs.mbs2.epics.server.entity.User;
import rs.mbs2.epics.server.session.dao.localinterface.AlbumDaoLocal;
import rs.mbs2.epics.server.session.dao.localinterface.CommentDaoLocal;
import rs.mbs2.epics.server.session.dao.localinterface.PhotoDaoLocal;
import rs.mbs2.epics.server.session.dao.localinterface.UserDaoLocal;

@SuppressWarnings("serial")
public class HomeController extends HttpServlet {

	private static Logger log = Logger.getLogger(HomeController.class);
	
	@EJB
	private PhotoDaoLocal photoDao;
	
	@EJB
	private AlbumDaoLocal albumDao;
	
	@EJB
	private UserDaoLocal userDao;
	
	@EJB
	private CommentDaoLocal commentDao;
	
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		System.out.println("HomeController.doGet()");
		
		// n photos
		List<Photo> nPhotos = photoDao.getNPhotos(10);
		if(nPhotos != null)
			log.info(new Date() + " - " + nPhotos.size() + " photos prepared");
		else
			log.error(new Date() + " - error pulling N photos");
		request.setAttribute("nPhotos", nPhotos);

		
		User user1 = (User) request.getSession().getAttribute("user");
		
		
		
		if(user1 != null) {
			User user = userDao.findById(user1.getId());
			request.getSession().setAttribute("user", user);

			List<Album> albums = albumDao.findAllAlbumsFromUser(user.getId());
			request.setAttribute("userAlbums", albums);
			
//			System.out.println("user : " + user.getFirstname());
			
			List<Comment> comments = commentDao.findUserComments(user.getId());
			
			/*
			if(user.getProfileImage() == null )
				System.out.println("user profile image == null");
			
			if(user.getAlbums() == null )
				System.out.println("user albums == null");
			
			if(user.getRatings() == null )
				System.out.println("user ratings == null");
			
			if(user.getFollowers() == null )
				System.out.println("user followers == null");
			*/
			
			request.setAttribute("recentComments", comments);
		}
		
		getServletContext().getRequestDispatcher("/home.jsp").forward(request, response);
		
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
	
}
